$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'goods/goods/list',
        datatype: "json",
        colModel: [
            { label: 'spu', name: 'goodsId', index: 'goods_id', width: 50, key: true,
                formatter:function(value,options,row){
                    return "<a onclick='jumpZiyun("+value+","+ row.stageType +")'>"+ value +"</a>";
                }
            },
            { label: '商品编号', name: 'goodsNo', index: 'goods_no', width: 80 },
            { label: '商品名称', name: 'name', index: 'name', width: 80,
                formatter:function(value,options,row){
                    return "<a onclick='jumpZiyun("+row.goodsId+","+ row.stageType +")'>"+ value +"</a>";
                }
            },
            { label: '分类', name: 'categoryId', index: 'category_id', width: 80 },
            // { label: '品牌ID', name: 'brandId', index: 'brand_id', width: 80 },
            { label: '无库存销售', name: 'noStore', index: 'no_store', width: 60,
                formatter:function(value,options,row){
                    if(value){
                        return '是';
                    }else{
                        return '否';
                    }
                }
            },
            { label: '上下架状态', name: 'marketable', index: 'marketable', width: 80 ,
                formatter:function(value,options,row){
                    if(value == 'puton'){
                        return '上架';
                    }else if(value == 'delete'){
                        return '删除';
                    }else if(value == 'pulloff'){
                        return '下架';
                    }
                }
            },
            { label: '排序', name: 'goodsOrder', index: 'goods_order', width: 80 },
            { label: '单位', name: 'unit', index: 'unit', width: 60 },
            { label: '审核状态', name: 'examineStatus', index: 'examine_status', width: 60 ,align:'center',
                formatter: function (value, options, row) {
                    if (value == 0) {
                        return '未审核';
                    }else if (value == 1) {
                        return '审核通过';
                    }else if (value == 2) {
                        return '审核失败';
                    }
                }
            },
            // { label: '商品简介', name: 'brief', index: 'brief', width: 80 },
            // { label: '视频url', name: 'videoUrl', index: 'video_url', width: 80,hidden:true },
            // { label: '默认图片urls', name: 'imageUrls', index: 'image_urls', width: 80 },
            // { label: '详细介绍图片urls', name: 'infoUrls', index: 'info_urls', width: 80,hidden:true },
            { label: '配送及售后', name: 'afterSale', index: 'after_sale', width: 80,hidden:true },
            { label: '起订量', name: 'minBuyNum', index: 'min_buy_num', width: 80,hidden:true },
            { label: '购买类型', name: 'goodsType', index: 'goods_type', width: 80,
                formatter: function (value, options, row) {
                    if (value == 'copy') {
                        return '复印纸';
                    }else if (value == 'design') {
                        return '设计商品';
                    }else if (value == 'paper') {
                        return '大纸商品';
                    }else if (value == 'standard') {
                        return '普通商品';
                    }else if (value == 'print') {
                        return '印刷商品';
                    }else if (value == 'fast') {
                        return '快印商品';
                    }else if (value == 'material') {
                        return '广告物料';
                    }
                } },
            { label: '上架平台', name: 'stageType', index: 'stage_type', width: 60 ,align:'center',
                formatter: function (value, options, row) {
                    if (value == 0) {
                        return '紫云/pop';
                    }else if (value == 1) {
                        return '紫云网';
                    }else if (value == 2) {
                        return 'pop平台';
                    }
                }
            },
            { label: '关联设计id', name: 'relateDesignIds', index: 'relate_design_ids', width: 80 },
            { label: '关键字', name: 'keywords', index: 'keywords', width: 80,hidden:true },
            { label: '运费模板id', name: 'freightId', index: 'freight_id', width: 80,hidden:true },
            { label: '是否供应商  1：自营，0：供应商', name: 'self', index: 'self', width: 30,
                formatter:function(value){
                    if(value == true){
                        return '自营'
                    }else{
                        return '供应商'
                    }
                }
            },
            { label: '卖家ID', name: 'sellerId', index: 'seller_id', width: 30 },
            { label: '模板图片id集合', name: 'goodsTemplateIds', index: 'goods_template_ids', width: 80,hidden:true },
            { label: '是否屏蔽（true：是；false：否）', name: 'disabled', index: 'disabled', width: 80 ,hidden:true},
            { label: '创建人', name: 'createName', index: 'create_name', width: 50 },
            { label: '创建时间', name: 'createTime', index: 'create_time', width: 80 },
            { label: '操作', name: 'operation',  width: 60 , align:'center',title:false,
                formatter:function(value, options, row){
                    var html = '<li class="dropdown" style="list-style: none;position: absolute;width: 60px;right: auto;left: auto;"><a href="#" style="margin:0 auto;text-decoration:none;" class="dropdown-toggle" data-toggle="dropdown">操作</a>';
                    html += '<ul class="dropdown-menu"  style="min-width:100%;font-size: 12px;">';
                    var operations = [];
                    operations.push('<li><a href="javascript:;" onclick="return editorGoods('+ options.rowId +');">编辑</a></li><li class="divider"></li>');
                    operations.push('<li><a href="javascript:;" onclick="return putonGoods('+ options.rowId +');">上架</a></li><li class="divider"></li>');
                    operations.push('<li><a href="javascript:;" onclick="return pulloffGoods('+ options.rowId +');">下架</a></li><li class="divider"></li>');
                    operations.push('<li><a href="javascript:;" onclick="return deleteGoods('+ options.rowId +');">删除</a></li><li class="divider"></li>');
                    html += operations.join("")
                    html += '</ul></li>';
                    return html;
                }
            }
        ],
        viewrecords: true,
        height: 700,
        rowNum: 25,
        rowList : [25,30,50],
        rownumbers: true,
        rownumWidth: 25,
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page",
            rows:"limit",
            order: "order"
        },
        gridComplete:function(){
            //隐藏grid底部滚动条
            $("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
        }
    });

    // 下列两个方法需要将其转换成对应远程调用
    //页面加载完毕,获得品牌列表
    $.get(baseURL + "goods/goodsbrand/allList", function(r){
        vm.goodBrands = r.brandEntityList;
    });
    //页面加载完毕,获得运费列表
    $.get(baseURL + "freightages/freighttemplate/allList", function(r){
        vm.freightTemplates = r.freightTemplateList;
    });

});

//点击商品id跳转到紫云网
function jumpZiyun(goodsId,stageType){
    var rowData = $("#jqGrid").jqGrid('getRowData',goodsId);
    var goodsTypeStr = rowData.goodsType;
    var goodsType = change(goodsTypeStr);
    if(stageType == 0 || stageType == 1){
        window.open("//www.11ziyun.com/goods/"+goodsId);
    }else if (stageType == 2){
        window.open("//mall.11ziyun.com/mall/skuProductDetails.do?goodsId="+ goodsId +"&goodsType="+goodsType);
    }
}
function change(value){
    if (value == '复印纸') {
        return 'copy';
    }else if (value == '设计商品') {
        return 'design';
    }else if (value == '大纸商品') {
        return 'paper';
    }else if (value == '普通商品') {
        return 'standard';
    }else if (value == '印刷商品') {
        return 'print';
    }else if (value == '快印商品') {
        return 'fast';
    }else if (value == '广告物料') {
        return 'material';
    }
}



//编辑商品
function editorGoods(goodsId){
    //将容器全部重置
    vm.showList = false;
    vm.title = "详细";
    vm.goods={delImageIds:[]};
    vm.goodsProductList={};
    vm.designGood={};
    vm.attributeNames=[];
    vm.craftNames=[];
    vm.getInfo(goodsId);
    vm.imageList=[];
    vm.infoList=[];
    //视频容器
    vm.videoEntity={};
}
//上架
function putonGoods(goodsId){
    vm.updateStatus(goodsId,"puton")
}
//下架
function pulloffGoods(goodsId){
    vm.updateStatus(goodsId,"pulloff")
}
//删除
function deleteGoods(goodsId){
    vm.updateStatus(goodsId,"delete")
}
// function info(goodsId){
//     vm.showList = false;
//     vm.title = "详细";
//     vm.goods={};
//     vm.goodsProductList={};
//     vm.designGood={};
//     vm.attributeNames=[];
//     vm.craftNames=[];
//     vm.getInfo(goodsId);
// }

var vm = new Vue({
    el:'#rrapp',
    data:{
        showList: true,
        title: null,
        goods: {
            delImageIds:[],
            stepPrice:null,
            popStepPrice:null,
        },
        goodsProductList:{},
        designGood:{},
        attributeNames:[],
        craftNames:[],
        goodBrands:{},
        freightTemplates:{},
        //图片容器
        imageList:[],infoList:[],
        infoIds:[],imageIds:[],
        //图片上传暂存容器
        goodsImage: {},
        //视频容器
        videoEntity:{},
        designQuery:{
            spu:'',
            name:''
        },
        q:{
            name:"",
            goodsId:"",
            marketable:'',
            goodsType:'',
            examineStatus:'',
        },
        attributeAndCraftData:{},
        copyAttributeAndCraftData:{},
        recordAttributeAndCraftData:{},
        machinePriceLayer:false,
        materialPriceLayer:false,
        craftPriceLayer:false,
        fastGroupPricelayer:false,
        attributeAndCraftLayer:false,
        //自定义选项dialog
        addOptionDialog:false,
        good:{},
        addItemList:[],
        //报价编辑
        quoteAttributeLayer:false,
        allQuoteTemplate:{},
        copyAllQuoteTemplate:{},
        goodsTemplateEntity:{},
        canPush:true,
        price:null,
        addPrivateOption:{
            optionName:null,
            optionValue:null,
        },
        unitLibraryList:null,
        priceDialog:false,
        stepPriceList:[],
        stepType:null,
    },
    methods: {
        query: function () {

            vm.reload();
        },
        // add: function(){
        // 	vm.showList = false;
        // 	vm.title = "新增";
        // 	vm.goods = {};
        // },
        addDesign: function(){
            vm.designQuery={spu:'',name:''}
            vm.myDesignQuery();
            layer.open({
                type: 1,
                skin: 'layui-layer-molv',
                title: "关联设计服务",
                area: ['510px', '500px'],
                shadeClose: false,
                content: jQuery("#designLayer"),
                btn: ['确定','取消'],
                btn1:function(){
                    var designId = $("#designJqGrid").getGridParam("selrow");
                    // //下列判断需完善
                    if(designId == null){
                        return;
                    }
                    //绑定designGoodsId到goods上
                    var goodId = vm.goods.goodsId;
                    //下列方法需要将其改为远程调用
                    $.get(baseURL + "goods/goods/addDesign/"+goodId+"/"+designId, function(r){
                        //添加完毕,重新加载设计商品
                        vm.getInfo(goodId);
                        //关闭layer
                        layer.close(layer.index);
                    });
                }
            });
        },
        update: function (event) {
            var goodsId = getSelectedRow();
            if(goodsId == null){
                return ;
            }
            vm.showList = false;
            vm.title = "修改";

            vm.getInfo(goodsId)
        },
        //商品修改保存
        updateGood: function (event) {
            // if(vm.canPush){
            //     alert("有参数不全,不能发布")
            //     return ;
            // }
            //图片vm.imageList和vm.infoList
            var str1 = '';
            if(!isBlank(vm.imageList) && vm.imageList.length > 0){
                for(var i = 0;i<vm.imageList.length;i++){
                    str1 =  str1 + ','+vm.imageList[i].id;
                }
            }
            vm.goods.imageUrls = str1;
            var str2 = '';
            if(!isBlank(vm.imageList) && vm.imageList.length > 0) {
                for (var i = 0; i < vm.infoList.length; i++) {
                    str2 = str2 + ',' + vm.infoList[i].id;
                }
            }
            vm.goods.infoUrls = str2;
            if(!(vm.goods.goodsType == 'fast' || vm.goods.goodsType == 'print')){
                //产品信息相关
                vm.goods.goodsProductList = vm.goodsProductList;
                var url = "goods/goods/update";
                //addItemList
                vm.goods.itemList = vm.addItemList;
                $.ajax({
                    type: "POST",
                    url: baseURL + url,
                    contentType: "application/json",
                    data: JSON.stringify(vm.goods),
                    beforeSend: function () {
                        $("#saveBtn").attr({disabled:"disabled"});
                        console.info("按钮已经被禁用")
                    },
                    complete:function(){
                        $("#saveBtn").removeAttr("disabled");
                        console.info("按钮已经被恢复")
                    },
                    success: function(r){
                        if(r.code === 0){
                            alert('操作成功', function(index){
                                vm.reload();
                            });
                        }else{
                            alert(r.msg);
                        }
                    }
                });
            }else if (vm.goods.goodsType == 'fast' || vm.goods.goodsType == 'print'){
                console.info("开始发布")
                //发布报价商品
                console.info(vm.allQuoteTemplate)
                var quoteVo = {};
                quoteVo.goodsEntity = vm.goods;
                //QuoteVo.quoteProductBaseInfoVOList
                var list = [];
                for(var i = 0;i<vm.allQuoteTemplate.length;i++){
                    var QuoteProductBaseInfoVO = {};
                    //遍历普通
                    var tempList = [];
                    for(var j = 0;j<vm.allQuoteTemplate[i].normalAttributeOptionList.length;j++){
                        if(vm.allQuoteTemplate[i].normalAttributeOptionList[j].normalSelectedTempOptionList.length>0){
                            var tempObject = {};
                            //每一种规格的选项集合
                            tempObject.id = vm.allQuoteTemplate[i].normalAttributeOptionList[j].id;
                            tempObject.attributeName =vm.allQuoteTemplate[i].normalAttributeOptionList[j].attributeName;
                            var ids = [];
                            for(var v = 0;v<vm.allQuoteTemplate[i].normalAttributeOptionList[j].normalSelectedTempOptionList.length;v++){
                                ids.push(vm.allQuoteTemplate[i].normalAttributeOptionList[j].normalSelectedTempOptionList[v].id);
                            }
                            tempObject.normalSelectedOptionList = ids;
                            tempObject.normalDefaultOption = vm.allQuoteTemplate[i].normalAttributeOptionList[j].normalDefaultOption;
                            tempList.push(tempObject);
                        }
                    }
                    QuoteProductBaseInfoVO.normalAttributeOptionSelectedList = tempList;
                    // list.push(tempList);
                    //遍历材料
                    var quoteTempList = []; //选中材料列表
                    if(JSON.stringify(vm.allQuoteTemplate[i].materialAttributeOptionData) != '{}'){
                        for(var j= 0;j<vm.allQuoteTemplate[i].materialAttributeOptionData.materialAttributeOptionList.length;j++){
                            if(vm.allQuoteTemplate[i].materialAttributeOptionData.materialAttributeOptionList[j].materialSelectedOptionList.length>0){
                                //该材料有被选择
                                var tempObject = {};
                                tempObject.id = vm.allQuoteTemplate[i].materialAttributeOptionData.materialAttributeOptionList[j].id;//属性id
                                tempObject.attributeName = vm.allQuoteTemplate[i].materialAttributeOptionData.materialAttributeOptionList[j].attributeName;// 属性名称
                                tempObject.materialSelectedOptionList = vm.allQuoteTemplate[i].materialAttributeOptionData.materialAttributeOptionList[j].materialSelectedOptionList;//选中的材料选项
                                quoteTempList.push(tempObject);
                            }
                        }
                    }
                    QuoteProductBaseInfoVO.materialAttributeOptionSelectedList = quoteTempList;
                    QuoteProductBaseInfoVO.materialDefaultOptionName2 = vm.allQuoteTemplate[i].materialAttributeOptionData.materialDefaultOptionName2;
                    QuoteProductBaseInfoVO.categoryId = vm.allQuoteTemplate[i].categoryId;
                    QuoteProductBaseInfoVO.partsId = vm.allQuoteTemplate[i].partsId;
                    list.push(QuoteProductBaseInfoVO);
                }
                quoteVo.quoteProductBaseInfoVOList = list;
                //发布报价商品;
                $.ajax({
                    type: "POST",
                    url: baseURL + "goods/goods/updateQuoteGood",
                    contentType: "application/json",
                    data: JSON.stringify(quoteVo),
                    beforeSend: function () {
                        $("#saveBtn").attr({disabled:"disabled"});
                        console.info("按钮已经被禁用")
                    },
                    complete:function(){
                        $("#saveBtn").removeAttr("disabled");
                        console.info("按钮已经被恢复")
                    },
                    success: function (r) {
                        if (r.code === 0) {
                            // alert('操作成功', function (index) {
                            // });
                            //页面跳转
                            window.location.href = "/modules/goods/goods.html";
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            }
        },
        //下列方法废除
        // del: function (event) {
        //     var goodsIds = getSelectedRows();
        //     if(goodsIds == null){
        //         return ;
        //     }
        //
        //     confirm('确定要删除选中的记录？', function(){
        //         //下列方法需要将其改为远程调用
        //         // $.ajax({
        //         //     type: "POST",
        //         //     url: baseURL + "goods/goods/delete",
        //         //     contentType: "application/json",
        //         //     data: JSON.stringify(goodsIds),
        //         //     success: function(r){
        //         //         if(r.code == 0){
        //         //             alert('操作成功', function(index){
        //         //                 $("#jqGrid").trigger("reloadGrid");
        //         //             });
        //         //         }else{
        //         //             alert(r.msg);
        //         //         }
        //         //     }
        //         // });
        //     });
        // },
        getInfo: function(goodsId){
            // 下列方法需要将其改为远程调用
            $.get(baseURL + "goods/goods/info/"+goodsId, function(r){
                if(r.code == 0){
                    vm.goods = r.goods;
                    vm.goodsProductList = r.goodsProductList;
                    vm.unitLibraryList = r.unitLibraryList;
                    if(vm.goods.attributeNames != null){
                        vm.attributeNames = vm.goods.attributeNames.split(",");
                    }
                    // 切割工艺需要判断是否为空
                    if(vm.goods.craftNames!= null){
                        vm.craftNames = vm.goods.craftNames.split(",");
                    }
                    if(r.designGood != null){
                        vm.designGood = r.designGood;
                    }
                    //默认图片处理imageList:[]
                    if(r.imageList != null){
                        vm.imageList = r.imageList;
                    }
                    //详细图片处理infoList:[]
                    if(r.infoList != null){
                        vm.infoList = r.infoList;
                    }
                    if(r.goodsTemplateEntity != null){
                        vm.goodsTemplateEntity = r.goodsTemplateEntity;
                    }
                    //视频
                    if(r.videoEntity != null){
                        vm.videoEntity = r.videoEntity;
                    }
                    if(r.attributeAndCraftData != null){
                        vm.attributeAndCraftData = r.attributeAndCraftData;
                        vm.copyAttributeAndCraftData = JSON.parse(JSON.stringify(r.attributeAndCraftData));//深克隆
                        vm.recordAttributeAndCraftData = JSON.parse(JSON.stringify(r.attributeAndCraftData));//深克隆
                        vm.goods.delImageIds = [];
                    }
                    if(r.allQuoteTemplate != null){
                        vm.allQuoteTemplate = r.allQuoteTemplate;
                        vm.copyAllQuoteTemplate = JSON.parse(JSON.stringify(r.allQuoteTemplate));//深克隆
                    }
                    Vue.nextTick(function () {
                        vm.loadOss();
                    });
                }else{
                    // alert(r.msg);
                    vm.$confirm(r.msg, '温馨提示', {
                        confirmButtonText: '确定',
                        type: 'warning'
                    }).then(() => {
                        //页面跳转
                        location.reload()
                    });
                }
            });


        },
        reset:function(){
            vm.q.name= '';
            vm.q.goodsId='';
            vm.q.marketable = '';
            vm.q.goodsType = '';
            vm.q.examineStatus = '';
        },
        reload: function (event) {
            vm.showList = true;
            vm.goods={delImageIds:[]};
            vm.goodsProductList={};
            vm.designGood={};
            vm.attributeNames=[];
            vm.craftNames=[];
            vm.imageList=[];
            vm.infoList=[];
            vm.designQuery={spu:'',name:''};
            vm.good={};
            vm.addItemList=[]
            var page = $("#jqGrid").jqGrid('getGridParam','page');
            $("#jqGrid").jqGrid('setGridParam',{
                page:page,
                postData:{
                    name:vm.q.name,
                    goodsId:vm.q.goodsId,
                    marketable:vm.q.marketable,
                    goodsType:vm.q.goodsType,
                    examineStatus:vm.q.examineStatus,
                },
            }).trigger("reloadGrid");
        },
        //关联设计服务jqGrid查询
        myDesignQuery:function(){
            $("#designJqGrid").jqGrid({
                url: baseURL + 'goods/goods/designList',
                datatype: "json",
                colModel: [
                    { label: 'spu', name: 'goodsId', index: 'goods_id', key: true },
                    { label: '商品编号', name: 'goodsNo', index: 'goods_no', },
                    { label: '商品名', name: 'goodsNo', index: 'goods_no',},
                ],
                viewrecords: true,
                height: 385,
                rowNum: 10,
                rowList : [10,30,50],
                rownumbers: true,
                rownumWidth: 25,
                autowidth:true,
                multiselect: true,
                pager: "#designJqGridPager",
                jsonReader : {
                    root: "page.list",
                    page: "page.currPage",
                    total: "page.totalPage",
                    records: "page.totalCount"
                },
                prmNames : {
                    page:"page",
                    rows:"limit",
                    order: "order"
                },
                gridComplete:function(){
                    //隐藏grid底部滚动条
                    $("#designJqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
                }
            });
        },
        reloadDesign: function (event) {
            var page = $("#designJqGrid").jqGrid('getGridParam','page');
            $("#designJqGrid").jqGrid('setGridParam',{
                page:page,
                postData:{
                    'spu': vm.designQuery.spu,
                    'name': vm.designQuery.name
                },
            }).trigger("reloadGrid");
        },
        //删除默认图片
        delImage:function(index,id){
            vm.imageList.splice(index,1);
            //定义删除图片的ids
            vm.goods.delImageIds.push(id);
        },
        //删除详细图片
        delInfo:function(index,id){
            vm.infoList.splice(index,1);
            vm.goods.delImageIds.push(id);
        },
        //删除视频
        delVideo:function(id){
            vm.videoEntity = {};
            vm.goods.delImageIds.push(id);
        },
        //更新spu状态
        updateStatus:function(goodsId,status){
            // 下列方法需要将其改为远程调用
            $.get(baseURL + "goods/goods/updateStatus/"+goodsId+"/"+status, function(r){
                if(r.msg == "success"){
                    alert("修改成功!")
                    //刷新查询
                    vm.reload();
                }
            });
        },
        //新版本规格工艺选择
        choiceNewAttributeAndCraft:function(){
            vm.attributeAndCraftLayer = true;
        },
        rollBack:function(){
            //深克隆
            vm.attributeAndCraftData = JSON.parse(JSON.stringify(vm.copyAttributeAndCraftData));
        },
        builderDate:function(){
            vm.good = {};
            // vm.recordAttributeAndCraftData
            // attributeAndCraftData
            var oldTemp = vm.build(vm.recordAttributeAndCraftData.attributeList,vm.recordAttributeAndCraftData.craftAttributeList);
            var oldData = JSON.parse(JSON.stringify(vm.good));//深克隆
            var newTemp = vm.build(vm.attributeAndCraftData.attributeList,vm.attributeAndCraftData.craftAttributeList);
            var newData = JSON.parse(JSON.stringify(vm.good));//深克隆
            //找出新生成的sku列表
            var oldItemList = oldData.itemList;
            var newItemList = newData.itemList;
            //循环新的newItemList,找出oldItemList没有的list
            var addItemList = [];
            for(var i = 0;i<newItemList.length;i++){
                // // var array = newItemList[i].getKeyArray("optionId")
                // var newArray = vm.getKeyArray(newItemList[i].spec)
                // var oldArray = vm.getKeyArray(oldItemList[i].spec)
                // //循环newArray,将oldArray里没有的item放入新建集合
                var flag = true;
                for(var j = 0;j<oldItemList.length;j++){
                    if(JSON.stringify(oldItemList[j].spec) == JSON.stringify(newItemList[i].spec)){
                        flag = false;
                    }
                }
                if(flag){
                    //如果没有在旧集合中出现,则放入添加的list
                    addItemList.push(newItemList[i]);
                }
            }
            vm.addItemList = addItemList;
            //-----------------编辑操作新增加的规格值封装--oldAttributeDate--newAttributeDate
            // temp.attributeDate = attributeDate;
            // temp.craftDate = craftDate;
            var oldCraftDate = oldTemp.craftDate;
            var newCraftDate = newTemp.craftDate;
            var oldAttributeDate = oldTemp.attributeDate;
            var newAttributeDate = newTemp.attributeDate;
            //将新工艺放入旧的sku里
            var cra = [];
            for(var k = 0;k<newCraftDate.length;k++){
                if(JSON.stringify(newCraftDate[k].option) != '[]'){
                    for(var kk = 0;kk<newCraftDate[k].option.length;kk++){
                        cra.push( newCraftDate[k].option[kk].optionId);
                    }
                }
            }
            console.info(cra.join(","));
            //遍历sku列表
            for(var z = 0;z<vm.goodsProductList.length;z++){
                vm.goodsProductList[z].craftOptionIds = cra.join(",");
            }
            //在这里为省略工序,将工艺和规格一起处理
            vm.pushArray(oldCraftDate,oldAttributeDate);
            vm.pushArray(newCraftDate,newAttributeDate);
            var addAttributeData = [];
            for(var i = 0;i<oldAttributeDate.length;i++){
                var attributeData = {};
                attributeData.attribute = oldAttributeDate[i].attribute;
                var option = [];
                var oldOption = oldAttributeDate[i].option;
                var newOption = newAttributeDate[i].option;
                var oldOptionIds = vm.getKeyArray(oldOption);
                for(var j = 0;j<newOption.length;j++){
                    if(oldOptionIds.indexOf(newOption[j].optionId) == -1){
                        var temp = {optionId:newOption[j].optionId,optionName:newOption[j].optionName}
                        //是新添加的规格
                        option.push(temp);
                    }
                }
                attributeData.option = option;
                //如果option为空,就不插入
                if(!isBlank(option)){
                    addAttributeData.push(attributeData);
                }
            }
            vm.goods.addAttributeData = addAttributeData;
            //复制
            vm.copyAttributeAndCraftData = JSON.parse(JSON.stringify(vm.attributeAndCraftData));
            vm.attributeAndCraftLayer = false;
            //-----------------------------结束------------------------------
            //调一下标品校验工艺价
        },
        //定义一个方法,获得对象的所有key,返回数组
        getKeyArray:function(object){
            var array = [];
            for(var obj in object){
                // (obj[key]);
                array.push(object[obj].optionId)
            }
            return array;
        },
        //定义一个方法,将一个数组类的所有元素放进另外一个数组
        pushArray:function(array1,array2){
            for(var i =0;i< array1.length;i++){
                array2.push(array1[i]);
            }
        },
        build:function(attributeList,craftAttributeList){
            vm.attributeList = attributeList;
            vm.craftAttributeList = craftAttributeList;
            //第一步,选出被选中的规格和工艺
            var attributeDate = [];
            var craftDate = [];
            for(var i= 0;i<vm.attributeList.length;i++){
                var option = [];
                var attribute = {};
                attribute.attributeId = vm.attributeList[i].attributeId;
                attribute.attributeName = vm.attributeList[i].attributeName;
                //遍历被选中的option列表
                for(var j= 0;j<vm.attributeList[i].optionSelectedList.length;j++){
                    var op = vm.attributeList[i].optionSelectedList[j]
                    option.push({optionId:op.optionId,optionName:op.optionName})
                }
                attributeDate.push({attribute:attribute,option:option});
            }
            //第二部,将参与sku生成的工艺提取
            var joinSkuOptionIds = [];
            for(var i = 0;i<vm.craftAttributeList.length;i++){
                //判断这个工艺是否参与
                if(vm.craftAttributeList[i].joinAttribute){
                    //该工艺参与sku的生产
                    var option = [];
                    var attribute = {};
                    var joinSkuOption = [];
                    var joinSkuAttribute = {};
                    attribute.attributeId = vm.craftAttributeList[i].attributeId;
                    attribute.attributeName = vm.craftAttributeList[i].attributeName;
                    //遍历被选中的option列表
                    for(var j= 0;j<vm.craftAttributeList[i].optionSelectedList.length;j++){
                        var op = vm.craftAttributeList[i].optionSelectedList[j]
                        option.push({optionId:op.optionId,optionName:op.optionName})
                        //将这部分参与sku生成的工艺选项标记
                        joinSkuOption.push(op.optionId)
                    }
                    joinSkuAttribute = vm.craftAttributeList[i].attributeId;
                    attributeDate.push({attribute:attribute,option:option});
                    joinSkuOptionIds.push({attribute:joinSkuAttribute,option:joinSkuOption})
                }else{
                    //套用以前的工艺生成方式
                    var option = [];
                    var attribute = {};
                    attribute.attributeId = vm.craftAttributeList[i].attributeId;
                    attribute.attributeName = vm.craftAttributeList[i].attributeName;
                    //遍历被选中的option列表
                    for(var j= 0;j<vm.craftAttributeList[i].optionSelectedList.length;j++){
                        var op = vm.craftAttributeList[i].optionSelectedList[j]
                        option.push({optionId:op.optionId,optionName:op.optionName})
                    }
                    craftDate.push({attribute:attribute,option:option})
                }
            }
            //第三部,组合数据出最终数据原型

            vm.good.specificationItems = attributeDate;
            console.info("attributeDate:"+attributeDate)
            vm.good.craftAttributes = craftDate;
            //将工艺添加到,原本的sku矩阵
            vm.good.joinSkuOptionIds = joinSkuOptionIds;
            vm.createItemList();
            vm.addCraft();
            var temp = {};
            temp.attributeDate = attributeDate;
            temp.craftDate = craftDate;
            return temp;
            //--------------------------------------
        },
        //创建SKU列表
        createItemList: function () {
            vm.good.itemList = [{
                spec: {},
                cra: {},
                store: '',
                unit: '',
                minBuyNum: '',
                marketable: 'puton',
                weight: '',
                totalPrice: '',
                totalPricePop: '',
                marketPrice: '',
                lMarketPrice: '',
                expandPrice: '',
                expandPricePop: '',
                cost: '',
                lCost: '',
                defaultProduct: false
            }]
            // vm.good.itemList=[{spec:{},price:0,num:99999,status:'0',isDefault:'0'} ];//列表初始化
            // vm.good.specificationItems={[{"attribute":{"attributeId":attributeId,"attributeName":attributeName}}
            //                              ,"option":[{"optionId":optionId,"optionName":optionName}]]}
            var items = vm.good.specificationItems;
            //item的长度是规格属性的个数
            for (var i = 0; i < items.length; i++) {
                vm.good.itemList = vm.addColumn(vm.good.itemList, items[i].attribute, items[i].option);
            }
            //创建完毕,为规格属性赋值
            var str = [];
            for (var i = 0; i < vm.good.specificationItems.length; i++) {
                str.push(vm.good.specificationItems[i].attribute.attributeName);
                // vm.attributeNames.push(vm.good.specificationItems[i].attribute.attributeName);
            }
            // vm.attributeNames = str;
        },
        //添加列数据
        //list:{"attribute":{"attributeId":attributeId,"attributeName":attributeName} ,"option":[{"optionId":optionId,"optionName":optionName}]}
        //columnName - attribute  ->{"attributeId":attributeId,"attributeName":attributeName}
        //columnValues - option ->[{"optionId":optionId,"optionName":optionName}]
        addColumn: function (list, columnName, columnValues) {
            var newList = [];
            //list的长度是需要克隆的记录条数
            for (var i = 0; i < list.length; i++) {
                var oldRow = list[i];
                //columnValues是每个规格属性选择值的个数
                for (var j = 0; j < columnValues.length; j++) {
                    var newRow = JSON.parse(JSON.stringify(oldRow));//深克隆
                    newRow.spec[columnName.attributeName] = columnValues[j];
                    newList.push(newRow);
                }
            }
            //vm.good.itemList[0].spec=[规格1:规格值1,规格2:规格值2]
            //vm.good.itemList[0].spec={"attribute":{"attributeId":attributeId,"attributeName":attributeName}
            //                           ,"option":{"optionId":optionId,"optionName":optionName}}
            return newList;
        },
        //向vm.good.itemList 的每一个item对象,添加一个cra{}
        addCraft: function () {
            //选择完成后的结果,用以装载进vm.good.itemList中的cra{}
            // var items= vm.good.craftAttributes;
            var items = vm.good.itemList;
            for (var i = 0; i < items.length; i++) {
                items[i].cra = vm.good.craftAttributes;
            }
            // for(var i=0;i<items.length;i++){
            //     vm.good.itemList= vm.addColumn( vm.good.itemList, items[i].attribute,items[i].option );
            // }
            //将选择结果返回展示
            for (var i = 0; i < vm.good.craftAttributes.length; i++) {
                vm.craftNames.push(vm.good.craftAttributes[i].attribute.attributeName);
            }
        },
        removeAttribute:function(value,row){
        },
        changePrice:function(value){
            if(value){
                //为true调用pop平台load价格
                vm.loadPrice('pop')
            }else{
                //为false调用紫云网load价格
                vm.loadPrice('ziyun')
            }
        },
        loadPrice:function(str){
            var coefficient = null;
            if(str == 'pop' && !isBlank(vm.goods.popPriceCoefficient)){
                coefficient  = vm.goods.popPriceCoefficient;
                if(!isBlank(vm.price)){
                    vm.goods.popPrice = vm.price * vm.goods.popPriceCoefficient;
                }
            }else if(str == 'ziyun' && !isBlank(vm.goods.ziyunPriceCoefficient)){
                coefficient  = vm.goods.ziyunPriceCoefficient;
                if(!isBlank(vm.price)){
                    vm.goods.price = vm.price * vm.goods.ziyunPriceCoefficient;
                }
            }
            if(coefficient != null){
                for(var i = 0;i<vm.goodsProductList.length;i++){
                    if(!isBlank(vm.goodsProductList[i].cost)){
                        vm.goodsProductList[i].totalPrice = vm.goodsProductList[i].cost * coefficient;
                        if(!isBlank(vm.goodsProductList[i].lCost)){
                            vm.goodsProductList[i].expandPrice = vm.goodsProductList[i].lCost * coefficient;
                        }
                    }
                }
                if(!isBlank(vm.addItemList)){
                    for(var i = 0;i<vm.addItemList.length;i++){
                        if(!isBlank(vm.addItemList[i].cost)){
                            vm.addItemList[i].totalPrice = vm.addItemList[i].cost * coefficient;
                            if(!isBlank(vm.addItemList[i].lCost)){
                                vm.addItemList[i].expandPrice = vm.addItemList[i].lCost * coefficient;
                            }
                        }
                    }
                }
            }
        },
        //刷新全部商品缓存
        refreshAllCache:function(){
            this.$confirm('此操作将刷新全部商品缓存, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                $.ajax({
                    type:"POST",
                    url:baseURL+"goods/goods/refreshAllCache",
                    contentType: "application/json",
                    success:function(r){
                        if(r.code == 0){
                            alert("刷新成功!")
                        }else{
                            alert("刷新失败!")
                        }
                    }
                })
                this.$message({
                    type: 'success',
                    message: '删除成功!'
                });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        // solveBug:function(){
        //     $.ajax({
        //         type:"POST",
        //         url:baseURL+"goods/goods/solveBug",
        //         contentType: "application/json",
        //         success:function(r){
        //             if(r.code == 0){
        //                 alert("刷新成功!")
        //             }else{
        //                 alert("刷新失败!")
        //             }
        //         }
        //     })
        // },
        loadOss:function(){
            /* oss上传 */
            $.files_up_oss({
                id: ["upload1", "upload2","upload3"],//按钮id
                url: "/sys/oss/getSignature",
                dir: "erp/pop/test/goods/goodsImages/",
                file_type: "jpg,png,gif,psd,ai,cdr,eps,ppt,word,excel,pdf,tiff,rar,zip,7z,gif,AVI,WMV,RM,RMVB,MPEG1,MPEG2,MPEG4,3GP,ASF,SWF,VOB,DAT,MOV,M4V,FLV,F4V,MKV,TIF",
                size: "100mb",//mb
                view_url: "https://ziyunoss.oss-cn-hangzhou.aliyuncs.com/"
            }, function (index_number, json) {
                if (json.Status == 'OK') {
                    // $('#image' + (index_number + 1)).attr('src', 'https://ziyunoss.oss-cn-hangzhou.aliyuncs.com/' + json.filename);
                    //将文件信息存放到图片集中
                    if (index_number == 0) {
                        //商品默认图片
                        vm.goodsImage.imageUrl = json.filename;
                        vm.goodsImage.type = 0;
                        $.ajax({
                            type: "POST",
                            url: baseURL + "goodsImage/goodsimage/saveImage",
                            contentType: "application/json",
                            data: JSON.stringify(vm.goodsImage),
                            success: function (r) {
                                if (r.code === 0) {
                                    vm.imageIds.push(r.id);
                                    vm.imageList.push({"imageUrl": json.filename, "id": r.id});
                                    // console.info(vm.imageUrls)
                                    // alert("上传图片成功")
                                } else {
                                    alert(r.msg);
                                }
                            }
                        });
                    } else if(index_number == 1){
                        //商品详细介绍图片
                        vm.goodsImage.imageUrl = json.filename;
                        vm.goodsImage.type = 1;
                        $.ajax({
                            type: "POST",
                            url: baseURL + "goodsImage/goodsimage/saveImage",
                            contentType: "application/json",
                            data: JSON.stringify(vm.goodsImage),
                            success: function (r) {
                                if (r.code === 0) {
                                    vm.infoIds.push(r.id);
                                    vm.infoList.push({"imageUrl": json.filename, "id": r.id});
                                    // alert("上传图片成功")
                                } else {
                                    alert(r.msg);
                                }
                            }
                        });
                    } else{//上传视频
                        vm.goodsImage.imageUrl = json.filename;
                        vm.goodsImage.type = 3;
                        $.ajax({
                            type: "POST",
                            url: baseURL + "goodsImage/goodsimage/saveImage",
                            contentType: "application/json",
                            data: JSON.stringify(vm.goodsImage),
                            success: function (r) {
                                if (r.code === 0) {
                                    // vm.infoIds.push(r.id);
                                    vm.goods.videoUrl = r.id;
                                    vm.videoEntity = {"imageUrl": json.filename, "id": r.id};
                                    // vm.infoUrls.push({"filename": json.filename, "fileId": r.id});
                                    // alert("上传图片成功")
                                } else {
                                    alert(r.msg);
                                }
                            }
                        });
                    }
                } else {
                    alert("出现异常,请联系管理员!")
                }
                alert("上传图片成功")
            });
        },
        //报价数据回滚
        rollbackQuote:function(){
            //报价回滚
            vm.allQuoteTemplate = JSON.parse(JSON.stringify(vm.copyAllQuoteTemplate));
        },
        buildQuoteData:function(){

            //编辑
            vm.copyAllQuoteTemplate = JSON.parse(JSON.stringify(vm.allQuoteTemplate));
            //关闭
            vm.quoteAttributeLayer = false;
            //调一下校验的方法-->工艺价和机器

            vm.quotevalidator();
        },
        countPrice:function(){
            console.info("调用远程接口返回价格")
            var idList = [];
            //默认材料不为空!
            for(var j = 0;j<vm.allQuoteTemplate.length;j++){
                var vo = {};
                //增加分类id和商务印刷和数码快印
                if(vm.goods.goodsType == 'print'){
                    vo.erpSellerFlag = false
                }else if(vm.goods.goodsType == 'fast'){
                    vo.erpSellerFlag = true
                }
                vo.categoryId = vm.goods.categoryId;
                var ids  = [];
                //partsId   categoryId
                if(vm.allQuoteTemplate.length > 1){
                    //有多个部件,则放部件,否则放分类
                    vo.partsId = vm.allQuoteTemplate[j].partsId;
                }else{
                    vo.partsId = vm.allQuoteTemplate[j].categoryId;
                }
                if(JSON.stringify(vm.allQuoteTemplate[j].materialAttributeOptionData) != '{}'){
                    if(!isBlank(vm.allQuoteTemplate[j].materialAttributeOptionData.materialDefaultOptionName2)){
                        ids.push(vm.allQuoteTemplate[j].materialAttributeOptionData.materialDefaultOptionName2);
                    }else{
                        console.info("报错哦")
                    }
                }
                for(var k = 0;k<vm.allQuoteTemplate[j].normalAttributeOptionList.length;k++){
                    if(!isBlank(vm.allQuoteTemplate[j].normalAttributeOptionList[k].normalDefaultOption)){
                        ids.push(vm.allQuoteTemplate[j].normalAttributeOptionList[k].normalDefaultOption);
                    }else{
                        console.info("报错哦")
                    }
                }
                vo.ids = ids;
                idList.push(vo)
            }
            //发送ajax请求
            $.ajax({
                type: "POST",
                url: baseURL + "goods/goods/countPrice",
                contentType: "application/json",
                data: JSON.stringify(idList),
                success: function (r) {
                    if (r.code === 0) {
                        var check = /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/;
                        var singlePriceCountOptionId = vm.getSinglePriceCount();
                        vm.price = r.result / singlePriceCountOptionId;
                        if(vm.goods.stageType == 0 || vm.goods.stageType == 1){
                            if(check.test(vm.goods.ziyunPriceCoefficient)){
                                vm.goods.price = vm.price * vm.goods.ziyunPriceCoefficient;
                            }
                        }
                        if (vm.goods.stageType == 0 || vm.goods.stageType == 2){
                            if(check.test(vm.goods.ziyunPriceCoefficient)){
                                vm.goods.popPrice = vm.price * vm.goods.popPriceCoefficient;
                            }
                        }
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        quotevalidator:function(){
            //获得所有的选项(包括规格选项)
            var ids = [];
            for(var i  = 0 ;i <vm.allQuoteTemplate.length;i++){
                for(var ii = 0;ii <vm.allQuoteTemplate[i].normalAttributeOptionList.length;ii++){
                    for(var iii = 0;iii <vm.allQuoteTemplate[i].normalAttributeOptionList[ii].normalSelectedTempOptionList.length;iii++){
                        ids.push(vm.allQuoteTemplate[i].normalAttributeOptionList[ii].normalSelectedTempOptionList[iii].id);
                    }
                }
            }
            //报价类的校验工艺价
            $.ajax({
                type: "POST",
                url: baseURL + "goods/goods/quotePrice",
                contentType: "application/json",
                async:false,
                data: ids.join(","),
                success: function (r) {
                    if(r.result == "ok"){
                        // alert("ok")
                        vm.canPush =  false;
                        return false;
                    }else if(r.result == "error"){
                        alert("报价工艺参数不全")
                        vm.canPush =  true;
                        return true;
                    }
                }
            });
            if (vm.goods.goodsType == 'print'){
                return vm.machineValidator();
            }
            if(vm.goods.goodsType == 'fast'){
                return vm.fastValidator();
            }
            return false;
        },
        //数码快印组合计价校验
        fastValidator:function(){
            //直接将所有选项全部按部件封装到后台校验
            var fastPriceVoList = [];
            for(var i = 0;i<vm.allQuoteTemplate.length;i++){
                var fastPriceVo = {};
                var selectedAttributeIds = [];
                var allSelectedOptionIds = [];
                for(var ii = 0;ii<vm.allQuoteTemplate[i].normalAttributeOptionList.length;ii++){
                    //可能会空
                    for(var iii = 0;iii<vm.allQuoteTemplate[i].normalAttributeOptionList[ii].normalSelectedTempOptionList.length;iii++){
                        selectedAttributeIds.push(vm.allQuoteTemplate[i].normalAttributeOptionList[ii].normalSelectedTempOptionList[iii].id);
                        //放入全部选项中
                        allSelectedOptionIds.push(vm.allQuoteTemplate[i].normalAttributeOptionList[ii].normalSelectedTempOptionList[iii].id);
                    }
                }
                fastPriceVo.selectedAttributeIds = selectedAttributeIds;
                //若材料不为空,则遍历
                if(JSON.stringify(vm.allQuoteTemplate[i].materialAttributeOptionData) != '{}'){
                    var selectedMaterialIds = [];
                    for(var ii = 0;ii<vm.allQuoteTemplate[i].materialAttributeOptionData.materialAttributeOptionList.length;ii++){
                        // var materialMap = {};
                        var optionKey = vm.allQuoteTemplate[i].materialAttributeOptionData.materialAttributeOptionList[ii].optionKey;
                        var materialIds = [];
                        for(var iii = 0;iii<vm.allQuoteTemplate[i].materialAttributeOptionData.materialAttributeOptionList[ii].materialSelectedOptionList.length;iii++){
                            // materialIds.push(vm.allQuoteTemplate[i].materialAttributeOptionData.materialAttributeOptionList[ii].materialSelectedOptionList[iii]);
                            selectedMaterialIds.push(vm.allQuoteTemplate[i].materialAttributeOptionData.materialAttributeOptionList[ii].materialSelectedOptionList[iii]);
                            allSelectedOptionIds.push(vm.allQuoteTemplate[i].materialAttributeOptionData.materialAttributeOptionList[ii].materialSelectedOptionList[iii]);
                        }
                        // materialMap.optionKey = optionKey;
                        // materialMap.materialIds = materialIds;
                        // selectedMaterialIds[optionKey] = materialIds;
                    }
                    fastPriceVo.selectedMaterialIds = selectedMaterialIds;

                }
                fastPriceVo.allSelectedOptionIds = allSelectedOptionIds;
                fastPriceVoList.push(fastPriceVo);
            }
            for(var j = 0;j<fastPriceVoList.length;j++){
                console.info("selectedAttributeIds:"+fastPriceVoList[j].selectedAttributeIds);
                console.info("selectedMaterialIds:"+JSON.stringify(fastPriceVoList[j].selectedMaterialIds));
            }
            //发送ajax请求校验数据结果
            $.ajax({
                type: "POST",
                url: baseURL + "goods/goods/verifyFastPrice",
                contentType: "application/json",
                async:false,
                data:JSON.stringify(fastPriceVoList),
                success: function (r) {
                    if(r.result == "ok"){
                        alert("校验通过")
                        vm.canPush =  false;
                        vm.countPrice();
                        return false;
                    }else{
                        alert("快印校验不通过:"+r.result)
                        vm.canPush =  true;
                        return true;
                    }
                }
            });
        },
        machineValidator:function(){
            //报价类的校验机器价
            //颜色选项
            var colorOptionIds = [];
            //尺寸选项
            var sizeOptionIds = [];
            //克重选项
            var weightOptionIds = [];
            for(var i = 0;i<vm.allQuoteTemplate.length;i++){
                for(var ii=0 ;ii<vm.allQuoteTemplate[i].normalAttributeOptionList.length;ii++){
                    if(vm.allQuoteTemplate[i].normalAttributeOptionList[ii].attributeName == '颜色'){
                        for(var iii = 0;iii<vm.allQuoteTemplate[i].normalAttributeOptionList[ii].normalSelectedTempOptionList.length;iii++){
                            colorOptionIds.push(vm.allQuoteTemplate[i].normalAttributeOptionList[ii].normalSelectedTempOptionList[iii].id);
                        }
                    }
                    if(vm.allQuoteTemplate[i].normalAttributeOptionList[ii].attributeName == '成品尺寸'){
                        for(var iii = 0;iii<vm.allQuoteTemplate[i].normalAttributeOptionList[ii].normalSelectedTempOptionList.length;iii++){
                            sizeOptionIds.push(vm.allQuoteTemplate[i].normalAttributeOptionList[ii].normalSelectedTempOptionList[iii].id);
                        }
                    }
                }
                if(JSON.stringify(vm.allQuoteTemplate[i].materialAttributeOptionData) != '{}'){
                    for(var j = 0;j<vm.allQuoteTemplate[i].materialAttributeOptionData.materialAttributeOptionList.length;j++){
                        // for(var jj = 0;jj<vm.allQuoteTemplate[i].materialAttributeOptionData.materialAttributeOptionList[j].materialSelectedOptionList.length;jj++){
                        Array.prototype.push.apply(weightOptionIds, vm.allQuoteTemplate[i].materialAttributeOptionData.materialAttributeOptionList[j].materialSelectedOptionList);
                        // }
                    }
                }
            }
            console.info("colorOptionIds:"+colorOptionIds);
            console.info("sizeOptionIds:"+sizeOptionIds);
            console.info("weightOptionIds:"+weightOptionIds);
            var printPriceVo = {};
            printPriceVo.colorOptionIds = colorOptionIds;
            printPriceVo.sizeOptionIds = sizeOptionIds;
            printPriceVo.weightOptionIds = weightOptionIds;
            $.ajax({
                type: "POST",
                url: baseURL + "goods/goods/verifyPrintPrice",
                contentType: "application/json",
                async:false,
                data: JSON.stringify(printPriceVo),
                success: function (r) {
                    if(r.result == "ok"){
                        // alert("ok")
                        vm.canPush =  false;
                        vm.countPrice();
                        return false;
                    }else{
                        alert("报价工艺参数不全"+r.result)
                        vm.canPush =  true;
                        return true;
                    }
                }
            });
        },

        //机器价格详情
        machinePrice:function(){
            vm.machinePriceLayer = true;
        },
        //材料价格详情
        materialPrice:function(){
            vm.materialPriceLayer = true;
        },
        //工艺价格详情
        craftPrice:function(){
            if((vm.goods.goodsType == 'fast' || vm.goods.goodsType == 'print')){
                vm.craftPriceLayer = true;
            }else{
                var craftAttribute = [];
                if(vm.attributeAndCraftData.craftAttributeList != null && vm.attributeAndCraftData.craftAttributeList.length>0){
                    for(var i = 0;i<vm.attributeAndCraftData.craftAttributeList.length;i++){
                        craftAttribute.push(vm.attributeAndCraftData.craftAttributeList[i].attributeId);
                    }
                }
                var data={templateId:vm.goodsTemplateEntity.templateId,attributeIds:craftAttribute};
                window.dialogCraftPricVm.setData(data);
            }
        },
        //工艺价格详情
        fastGroupPrice:function(){
            vm.fastGroupPricelayer = true;
        },
        //当普通选项的选项值删除了默认时,同步右侧的默认选项
        changeNormal:function(normalAttributeOption){
            var flag = true;
            for(var i = 0;i<normalAttributeOption.normalSelectedTempOptionList.length;i++){
                if(normalAttributeOption.normalSelectedTempOptionList[i].id ==normalAttributeOption.normalDefaultOption ){
                    //此时删除了默认选项重置
                    flag = false;
                }
            }
            if(flag){
                //此时删除了默认选项重置
                if(normalAttributeOption.normalSelectedTempOptionList.length == 1){
                    normalAttributeOption.normalDefaultOption = normalAttributeOption.normalSelectedTempOptionList[0].id;
                }else{
                    normalAttributeOption.normalDefaultOption = null;
                }
            }
        },
        //当某种材料的选中值改变时,若该材料是默认材料时,改变选项列表
        changeMaterial:function(materialAttributeOptionData,materialAttributeOption){
            //判断当前改变值得材料类型,是否是当前默认选中的材料类型
            if(materialAttributeOptionData.materialDefaultOption == materialAttributeOption.optionKey){
                //若是,则判断目前所改变值集合,是否包含选中材料类型的默认类型--->是否重置默认选中材料
                if(materialAttributeOption.materialSelectedOptionList.indexOf(materialAttributeOptionData.materialDefaultOptionName2) == -1){
                    //删除了默认选中的材料-->重置
                    if(materialAttributeOption.materialSelectedOptionList.length ==1 ){
                        //如果只剩下一个选项,则直接选中
                        materialAttributeOptionData.materialDefaultOptionName2 = materialAttributeOption.materialSelectedOptionList[0]
                    }else{
                        materialAttributeOptionData.materialDefaultOptionName2 = null;
                    }
                }
                //更新带选择的默认材料列表
                // materialAttributeOptionData.materialDefaultOptionName2List --->重新赋值
                //materialAttributeOption.materialSelectedOptionList为optionIds,取其对于的tem
                var temp = [];
                for(var i = 0;i<materialAttributeOption.materialOptionList.length;i++){
                    if(materialAttributeOption.materialSelectedOptionList.indexOf(materialAttributeOption.materialOptionList[i].id) != -1){
                        //放入
                        temp.push(materialAttributeOption.materialOptionList[i]);
                    }
                }
                materialAttributeOptionData.materialDefaultOptionName2List = temp;
            }
        },
        optionDialog:function(row){
            vm.addPrivateOption.attributeId = row.attributeId
            vm.addOptionDialog = true;
        },
        //保存增加选项
        savePrivateOption:function(){
            if(!isBlank(vm.goodsTemplateEntity.influenceSkuTotalPrice) && vm.addPrivateOption.attributeId == vm.goodsTemplateEntity.influenceSkuTotalPrice) {
                var re = /^[0-9]+$/;
                if (!re.test(vm.addPrivateOption.optionValue)) {
                    alert("该选项影响算价,请修正选项值为数字!")
                    return;
                }
            }
            //发送ajax请求生成私有选项
            $.ajax({
                type: "POST",
                url: baseURL + "goods/goodsattribute/newOption",
                contentType: "application/json",
                data:JSON.stringify(vm.addPrivateOption),
                // data:JSON.stringify(attribute),
                success: function (r) {
                    //重新加载规格选项
                    // vm.getAttributesByTemplateId();
                    if(r.code == 0){
                        if(r.goodsOptionEntity != null){
                            for(var i = 0;i<vm.attributeAndCraftData.attributeList.length;i++){
                                if(vm.attributeAndCraftData.attributeList[i].attributeId == r.goodsOptionEntity.attributeId){
                                    vm.attributeAndCraftData.attributeList[i].goodsOptionList.push(r.goodsOptionEntity);
                                }
                            }
                            vm.copyAttributeAndCraftData = JSON.parse(JSON.stringify(vm.attributeAndCraftData));
                        }else{
                            alert("新增选项异常,请联系管理员")
                        }
                    }
                }
            })
            vm.addOptionDialog = false;
        },
        //取消保存选项
        cancelPrivateOption:function(){
            //重置值
            vm.addPrivateOption.attributeId = null;
            vm.addPrivateOption.optionName = null;
            vm.addPrivateOption.optionValue = null;
            vm.addOptionDialog = false;
        },
        //提取报价算价数量参数--返回默认数量
        getSinglePriceCount(){
            if(vm.allQuoteTemplate != null){
                for(var i = 0;i<vm.allQuoteTemplate.length;i++){
                    for(var j = 0;j <vm.allQuoteTemplate[i].normalAttributeOptionList.length;j++){
                        if(vm.allQuoteTemplate[i].normalAttributeOptionList[j].attributeTypeValue == 'quantity'){
                            for(var k = 0;k<vm.allQuoteTemplate[i].normalAttributeOptionList[j].normalOptionList.length;k++){
                                if(vm.allQuoteTemplate[i].normalAttributeOptionList[j].normalOptionList[k].id == vm.allQuoteTemplate[i].normalAttributeOptionList[j].normalDefaultOption){
                                    return vm.allQuoteTemplate[i].normalAttributeOptionList[j].normalOptionList[k].optionName;
                                }
                            }
                        }
                    }
                }
            }
        },
        //改变默认sku
        changeDefault:function(index,str){
            if(str == 'product'){
                for(var i = 0;i<vm.goodsProductList.length;i++){
                    if(vm.goodsProductList[i].defaultProduct == true && i!= index){
                        vm.goodsProductList[i].defaultProduct = false;
                    }
                }
            }else{
                for (var productElement of vm.goodsProductList) {
                    productElement.defaultProduct = false;
                }
            }
            if(str == 'item'){
                for(var i = 0;i<vm.addItemList.length;i++){
                    if(vm.addItemList[i].defaultProduct == true && i!= index){
                        vm.addItemList[i].defaultProduct = false;
                    }
                }
            }else{
                for (var itemElement of vm.addItemList) {
                    itemElement.defaultProduct = false;
                }
            }
        },
        delRow: function (index, stepPriceList) {
            stepPriceList.splice(index, 1);
        },
        addStepPriceList: function () {
            vm.stepPriceList.push({startPrice: null, endPrice: null, coefficient: null})
        },
        openStepPrice:function(type){
            vm.stepType = type;
            if(type == 'ziyun'){
                if(!isBlank(vm.goods.stepPrice)){
                    vm.stepPriceList = JSON.parse(vm.goods.stepPrice);
                }
                vm.priceDialog = true;
            }else if(type == 'pop'){
                if(!isBlank(vm.goods.popStepPrice)){
                    vm.stepPriceList = JSON.parse(vm.goods.popStepPrice);
                }
                vm.priceDialog = true;
            }else{
                alert("阶梯价展示异常")
            }
        },
        closePriceDialog: function () {
            //将阶梯价清空
            vm.stepPriceList = [];
        },
        savePrice: function () {
            if (this.stepPriceValidator()) {
                return;
            }
            if(vm.stepType == 'ziyun'){
                if(!isBlank(vm.stepPriceList)){
                    vm.goods.stepPrice = JSON.stringify(vm.stepPriceList);
                }
                vm.priceDialog = false;
            }else if(vm.stepType == 'pop'){
                if(!isBlank(vm.stepPriceList)){
                    vm.goods.popStepPrice = JSON.stringify(vm.stepPriceList);
                }
                vm.priceDialog = false;
            }else{
                alert("阶梯价保存异常")
            }
        },
        stepPriceValidator:function(){
            for(var i = 0;i<vm.stepPriceList.length;i++){
                var stepPrice = vm.stepPriceList[i];
                if(isBlank(stepPrice.startPrice)){
                    alert("第"+(i+1)+"行阶梯价起始价格为空,请检查!");
                    return true;
                }
                if(isBlank(stepPrice.endPrice)){
                    alert("第"+(i+1)+"行阶梯价结束价格为空,请检查!");
                    return true;
                }
                if(isBlank(stepPrice.coefficient)){
                    alert("第"+(i+1)+"行阶梯价利润系数为空,请检查!");
                    return true;
                }
            }
            return false;
        }
    }
});
